﻿/*
Copyright (c) 2013, Douglas Stebila, Brendon Park, David Sweeney, Nathan Wills, Simon Lockhart, Thomas Phan
All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this
  list of conditions and the following disclaimer.

* Redistributions in binary form must reproduce the above copyright notice, this
  list of conditions and the following disclaimer in the documentation and/or
  other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.IO;
using System.Security.Cryptography;

namespace NMLE.HCE
{
    /// <summary>
    ///     Hashed Convergent Encryption algorythm. Provides methods to 
    ///     perform MLE convergent encryption with a hash check
    /// </summary>
    /// <typeparam name="THashAlgorithm">
    ///     The hash algorythm used to derive the key
    /// </typeparam>
    /// <typeparam name="TEncryptionAlgorithm">
    ///      The encryption algorythm used transform the message
    /// </typeparam>
    public class HCE<THashAlgorithm, TEncryptionAlgorithm>
        : MessageLockedAlgoritm<THashAlgorithm, TEncryptionAlgorithm>
        where THashAlgorithm : HashAlgorithm, new()
        where TEncryptionAlgorithm : SymmetricAlgorithm, new()
    {

        private Byte[] _key;
        private Byte[] _tag;

        /// <summary>
        ///     Creates a message locked decryptor object with the current
        ///     key, hash algorythm and, symetric algorythm.
        /// </summary>
        /// <returns>
        ///     A message locked decryptor object.
        /// </returns>
        public override ICryptoTransform GetDecryptor()
        {
            return new HCETransform<THashAlgorithm,TEncryptionAlgorithm>(
                Key,
                EncryptionDirection.Decrypt		
                );
        }


        /// <summary>
        ///     Creates a message locked encryptor object with the current
        ///     hash algorythm and symetric algorythm.
        /// </summary>
        /// <returns>
        /// </returns>
        public ICryptoTransform GetEncryptor(Stream message, Int32 keySize)
        {
            DeriveKey(message, keySize);
            return GetEncryptor();
        }

        /// <summary>
        ///     Creates a message locked encryptor object with the current
        ///     hash algorythm and symetric algorythm.
        /// </summary>
        /// <returns>
        /// </returns>
        public ICryptoTransform GetEncryptor(Stream message)
        {
            return GetEncryptor(message, LargestValidKey());
        }

        /// <summary>
        ///     Creates a message locked encryptor object with the current
        ///     hash algorythm and symetric algorythm.
        /// </summary>
        /// <returns>
        ///   
        /// </returns>
        public override ICryptoTransform GetEncryptor()
        {
            return new HCETransform<THashAlgorithm, TEncryptionAlgorithm>(
                Key,
                EncryptionDirection.Encrypt
                );
        }

        /// <summary>
        ///     Gets the MLE key for the given message     
        /// </summary>
        /// <param name="message">
        ///     Stream containing the message that will be encrypted
        /// </param>
        /// <param name="keySize">
        ///     A valid keysize to truncate the key too
        /// </param>
        public override void DeriveKey(Stream message, Int32 keySize)
        {
            message.Position = 0;
            _key = new byte[keySize/8];
            var hashAlg = new THashAlgorithm();
            var hash = hashAlg.ComputeHash(message);
            Array.Copy(hash,_key,Key.Length);
            message.Position = 0;
            _tag = new Rfc2898DeriveBytes(hash, Key, 1000).GetBytes(hash.Length);
        }

        /// <summary>
        ///     Gets the MLE key for the given message
        /// </summary>
        /// <param name="message">
        ///     Stream containing the message that will be encrypted
        /// </param>
        public override void DeriveKey(Stream message)
        {
            DeriveKey(message, LargestValidKey());
        }

        public void SetKey(byte[] keyBytes)
        {
            _key = keyBytes;
            _tag = new Rfc2898DeriveBytes(Key, Key, 1000).GetBytes(Key.Length);
        }

        /// <summary>
        ///     Gets or sets the secret key for the message locked crypto
        ///     algorithm.
        /// </summary>
        public override byte[] Key
        {
            get
            { 
                if (_key != null) 
                    return _key; 
                throw new InvalidOperationException(
                    "Cannot access key unless a key has been derived from a " +
                    "message"
                    ); 
            }
            set
            {
                _key = value;
                _tag = _tag = new Rfc2898DeriveBytes(_key, _key, 1000)
                    .GetBytes(_key.Length);
            }
        }

        /// <summary>
        ///     Gets or sets the secret key for the message locked crypto
        ///     algorithm.
        /// </summary>
        public override byte[] Tag
        {
            get
            {
                if (_tag != null)
                    return _tag;
                throw new InvalidOperationException(
                    "Cannot access tag unless a key has been derived from a " +
                    "message"
                    );
            }
            protected set
            {
                _tag = value;
            }
        }
    }
}
